# 角色和权限模型
from datetime import datetime
from app.extensions import db

class Permission(db.Model):
    """权限模型"""
    __tablename__ = 'permissions'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)
    description = db.Column(db.String(255))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<Permission {self.name}>'

class Role(db.Model):
    """角色模型"""
    __tablename__ = 'roles'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)
    description = db.Column(db.String(255))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 多对多关系：一个角色可以有多个权限
    permissions = db.relationship('Permission', secondary='role_permissions',
                                 backref=db.backref('roles', lazy='dynamic'))
    
    def __repr__(self):
        return f'<Role {self.name}>'
    
    def has_permission(self, permission_name):
        """检查角色是否拥有特定权限"""
        return any(p.name == permission_name for p in self.permissions)
    
    def add_permission(self, permission):
        """添加权限到角色"""
        if not self.has_permission(permission.name):
            self.permissions.append(permission)
    
    def remove_permission(self, permission):
        """从角色中移除权限"""
        if self.has_permission(permission.name):
            self.permissions.remove(permission)

# 关联表：角色和权限的多对多关系
role_permissions = db.Table(
    'role_permissions',
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id'), primary_key=True),
    db.Column('permission_id', db.Integer, db.ForeignKey('permissions.id'), primary_key=True)
)

# 关联表：用户和角色的多对多关系
user_roles = db.Table(
    'user_roles',
    db.Column('user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id'), primary_key=True)
)